#ifndef DOWNLOADMGR_H
#define DOWNLOADMGR_H

#include "episodes.h"
#include <QList>
#include <QFile>
#include <QObject>
#include <QNetworkAccessManager>
#include <QPointer>
#include <QNetworkReply>

class Download;
/** An object which downloads podcast episodes.
    @author Alan Ezust
 */
class DownloadMgr : public QObject
{
    Q_OBJECT
public:
    // Buffer 10k at a time on symbian:
#ifdef Q_OS_SYMBIAN
    enum {BufferSize = 80000};
#else
    enum {BufferSize = 800000};
#endif
    DownloadMgr(QObject* parent=0);

    Download* start(Episode& e);
    Download* getDownload(const Episode& e) const;

    void remove(Episode& e);

//    void handleError(QNetworkReply::NetworkError err);
public slots:
    /* Stop downloading episode */
    void abort(Episode& e);
protected slots:
    bool savePartial(Download* d);

    void downloadEpisodeFinished(QNetworkReply*);
    void updateProgress(qint64, qint64);
signals:
    /** Emitted when views displaying this episode need to be updated */
    void updateViews(const Episode&);
private:
    QHash<Episode, Download*> m_downloads;
    QHash<QNetworkReply*, Download*> m_replyHash;
    QNetworkAccessManager m_manager;
};

/** An Episode that is being downloaded by DownloadMgr. */
class Download : public QObject {
    Q_OBJECT
public:
    enum Status {NotStarted = 0, Downloading, Aborted, Complete};
    Download(Episode& episode, QObject* parent=0);
    ~Download();
    void start(QNetworkReply* reply);
    void abort();
    Episode& episode;
    QPointer<QNetworkReply> reply;
    QFile file;
    uint totalBytes, bytesWritten;
    uint progress;
    Status status;
};




#endif // DOWNLOADMGR_H
